<?php

namespace Utuo;

use Think\Controller;
use Think\Page;

class BackgroundController extends Controller {
	// 是否登录SESSION键名
	const IS_LOGINED = '_is_logined_';
	
	// 最后活动时间SESSION键名
	const LAST_ACTIVE = '_last_active_';
	
	/**
	 * 登录时间SESSION键名
	 *
	 * @var string
	 */
	const LOGIN_TIME = '_login_time_';
	
	/**
	 * 登录标记SESSION键名
	 *
	 * @var string
	 */
	const LOGIN_LABEL = '_login_label_';
	
	/**
	 * 登录相关SESSION名
	 *
	 * @var array
	 */
	private $sessionKeys = array ();
	
	/**
	 * 模块标题
	 *
	 * @var string
	 */
	private $moduleTitle;
	
	/**
	 * 控制器标题
	 *
	 * @var string
	 */
	private $controllerTitle;
	
	/**
	 * 每页显示条数
	 *
	 * @var int
	 */
	protected $pageSize = 10;
	
	/**
	 * 动作标题数组
	 *
	 * @var array
	 */
	private $actionTitles = array ();
	
	/**
	 * 动作导航数组
	 *
	 * @var array
	 */
	private $actionNavs = array ();
	
	/**
	 * 动作导航参数
	 *
	 * @var array
	 */
	private $actionNavParams = array ();
	
	/**
	 * 链接导航
	 *
	 * @var array
	 */
	private $linkNavs = array ();
	
	/**
	 * 链接导航标题
	 *
	 * @var string
	 */
	private $linkNavTitle = '链接导航';
	
	/**
	 * 登录 管理ID/合作商ID/客户ID
	 *
	 * @var integer
	 */
	protected $aid;
	
	/**
	 * 管理者id
	 *
	 * @var integer
	 */
	protected $adminId;
	
	/**
	 * 登录用户名字
	 *
	 * @var string
	 */
	protected $aname;
	
	/**
	 * 回调函数
	 * 
	 * @var unknown
	 */
	protected $callBack = array ();
	
	/**
	 * 跳转消息
	 *
	 * @var string
	 */
	private static $redirectMessage;
	
	/**
	 * 跳转时间
	 * 
	 * @var integer
	 */
	private static $redirectTime = 0;
	private $loginLog = null;
	
	// 合作商标记
	protected $partnerLabelKey = 'partnerLabel';
	protected $partnerLabel = '';
	protected $partnerConfig = array();
	
	// 合作商信息
	protected $partner = array();
	
	// 是否显示路径导航
	protected $pathVisible = true;
	
	/**
	 * 构造函数
	 */
	public function __construct() {
		if (C('LOGIN_LOG')) {
			$this->loginLog = \Utuo\LoginLog::getInstance();
		}
		
		{
		    // 域名跳转
		    if (strtolower($_SERVER['HTTP_HOST'])=='w.wmfl.cn'){
		        redirect(sprintf('http://%s%s',C('SITE_DOMAIN'),__SELF__));
		    }
		}
		
		$this->checkLogin();
		parent::__construct();
		$this->checkAuth();
		
	   // 合作商标记
// 	   $this->partnerLabel = I('partnerLabel');
// 	   $this->partnerLabel && $this->partnerConfig = M('Partner')->where(array('label'=>$this->partnerLabel))->find();
		
		/*\Utuo\UtuoLog::doLogPost("WmflBackground", array (
				'user' => array (
						'id' => $this->aid,
						'name' => $this->aname 
				) 
		));*/
	   
		$pid = 0;
		$cid = 0;
		$aid = 0;
		$uid = 0;
		$userName = session('name');
		if ( MODULE_NAME == 'Admin') {
			$uid = session('id');
		} elseif ( MODULE_NAME == 'Partner' ) {
			$pid = session('id');
			$uid = session(C("USER_AUTH_KEY"));
		} elseif ( MODULE_NAME == 'My' ) {
			$pid = session('pid');
			$cid = session('id');
			$uid = session(C("USER_AUTH_KEY"));
			$this->partner = $this->partnerConfig = M('Partner')->find($pid);
			$this->partnerLabel = $this->partnerConfig['label'];
		} else {
			$aid = session('id');
			$uid = session(C("USER_AUTH_KEY"));
		}
		\Utuo\UtuoLog::write("LogBackground", $pid, $cid, $aid, $uid, $userName);
	}
	
	/**
	 * 重构display
	 *
	 * @see \Think\Controller::display()
	 */
	protected function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
		$this->setModuleTitle($this->partner['name'].C('APP_TITLE'));
		$this->pathVisible && $this->assign('positionPath', $this->getPositionPath());
		$this->assign('actionNavs', $this->getActionNavs());
		$this->assign('linkNavs', $this->getLinkNavs());
		$this->assign('linkNavTitle', $this->getLinkNavTitle());
		$this->assign('controllerTitle', $this->getControllerTitle());
		$this->assign('actionTitle', $this->getActionTitle());
		$this->assign('moduleTitle', $this->getModuleTitle());
		C('TMPL_PARSE_STRING.__STYLE__', $this->getStylePath());
		return parent::display($templateFile, $charset, $contentType, $content, $prefix);
	}
	
	/**
	 * 设置是否显示路径
	 * @param boolean $show
	 */
	protected function setPathVisible($visible){
	    $this->pathVisible = $visible;
	}
	
	/**
	 * 获取当前风格路径
	 *
	 * @return string
	 */
	protected function getStylePath() {
		return __ROOT__ . '/Public/Style/' . MODULE_NAME . '/' . C('TMPL_DEFAULT_THEME', null, 'Default') . '/';
	}
	
	/**
	 * 添加页
	 */
	public function addAction() {
		$this->display('save');
	}
	
	/**
	 * 修改页
	 */
	public function modifyAction() {
		$model = CONTROLLER_NAME;
		$config = D($model)->getOneById();
		$this->assign(lcfirst($model), $config);
		$this->display("save");
	}
	
	/**
	 * 提交保存
	 */
	public function saveAction() {
		$this->submitPost(CONTROLLER_NAME);
	}
	/**
	 * AJAX返回正确信息
	 *
	 * @param string $msg
	 * @param array $extra
	 * @return \Utuo\BackgroundController
	 */
	protected function ajaxSuccess($msg = '操作成功', $extra = null, $redirectUrl = null, $redirectDelay = 1) {
		$data['error'] = 0;
		$data['msg'] = $msg;
		is_null($extra) or $data['extra'] = $extra;
		is_null($redirectUrl) or $data['redirect'] = array (
				'url' => $redirectUrl,
				'delay' => $redirectDelay * 1000 
		);
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($data));
	}
	
	/**
	 * AJAX返回错误信息
	 *
	 * @param string $msg
	 * @param array $extra
	 * @return \Utuo\BackgroundController
	 */
	protected function ajaxError($msg = '操作失败', $extra = null, $redirectUrl = null, $redirectDelay = 1) {
		$data['error'] = 1;
		$data['msg'] = $msg;
		is_null($extra) or $data['extra'] = $extra;
		is_null($redirectUrl) or $data['redirect'] = array (
				'url' => $redirectUrl,
				'delay' => $redirectDelay * 1000 
		);
		header('Content-Type:application/json; charset=utf-8');
		exit(json_encode($data));
	}
	
	/**
	 * 移除数据（放到到回收站，可以恢复）
	 *
	 * @param string $varModel
	 * @param string $msgError
	 * @param string $msgSucc
	 * @param string $varPK
	 * @param string $varField
	 */
	protected function ajaxRemove($varModel, $msgError = '移除失败', $msgSucc = '移除成功', $varPK = 'id', $varField = 'is_deleted') {
		isset($varModel) || $varModel = CONTROLLER_NAME;
		$id = I($varPK, 0, 'intval');
		
		if (false !== M($varModel)->where("$varPK=$id")->setField($varField, 1)) {
			
			$this->dispatchEvent(new Event("afterRemove"));
			$this->ajaxSuccess($msgSucc);
		} else {
			$this->ajaxError($msgError);
		}
	}
	
	/**
	 * 移除
	 */
	public function removeAction() {
		$this->ajaxRemove();
	}
	
	/**
	 * 删除
	 */
	public function deleteAction() {
		$this->ajaxDelete();
	}
	
	/**
	 * 恢复
	 */
	public function restoreAction() {
		$this->ajaxRestore();
	}
	
	/**
	 * 设置状态
	 */
	public function setStatusAction() {
		$this->ajaxSetStatus();
	}
	
	/**
	 * 事件监听
	 * 
	 * @param string $eventName 事件名称
	 * @param function $fun 处理函数句柄
	 */
	protected function addEventListener($eventName, $fun, $scope = 0) {
		$scope === 0 and $scope = $this;
		if ($this->callBack[$eventName])
			$this->callBack[$eventName] = array ();
		$this->callBack[$eventName][] = array (
				$fun,
				$scope 
		);
	}
	
	/**
	 * 事件分发
	 * 
	 * @param unknown $e
	 */
	protected function dispatchEvent($e) {
		foreach ($this->callBack[$e->eventName] as $v) {
			$v[0]($e, $v[1]);
		}
	}
	
	/**
	 * 恢复数据（从回收站里恢复）
	 *
	 * @param string $varModel
	 * @param string $msgError
	 * @param string $msgSucc
	 * @param string $varPK
	 * @param string $varField
	 */
	protected function ajaxRestore($varModel, $msgError = '恢复失败', $msgSucc = '恢复成功', $varPK = 'id', $varField = 'is_deleted') {
		isset($varModel) || $varModel = CONTROLLER_NAME;
		$id = I($varPK, 0, 'intval');
		if (M($varModel)->where("$varPK=$id")->setField($varField, 0)) {
			$this->dispatchEvent(new Event("afterRestore"));
			$this->ajaxSuccess($msgSucc);
		} else {
			$this->ajaxError($msgError);
		}
	}
	
	/**
	 * 删除数据（从数据库里删除，无法恢复）
	 *
	 * @param string $varModel
	 * @param string $msgError
	 * @param string $msgSucc
	 * @param string $varPK
	 */
	protected function ajaxDelete($varModel, $msgError = '删除失败', $msgSucc = '删除成功', $varPK = 'id') {
		isset($varModel) || $varModel = CONTROLLER_NAME;
		$id = I($varPK, 0, 'intval');
		if (M($varModel)->delete($id)) {
			$this->ajaxSuccess($msgSucc);
		} else {
			$this->ajaxError($msgError);
		}
	}
	
	// 设置状态
	protected function ajaxSetStatus($varModel, $varStatus = 'status') {
		isset($varModel) || $varModel = CONTROLLER_NAME;
		$status = I("status", 0, "intval");
		$id = I("id", 0, "intval");
		$d = D($varModel);
		if (false !== $d->where("id={$id}")->setField($varStatus, 1 - $status)) {
			$this->ajaxSuccess();
		} else {
			$this->ajaxError($d->getError());
		}
	}
	// 设置排序
	public function ajaxSort($varModel, $varStatus = 'sort') {
		isset($varModel) || $varModel = CONTROLLER_NAME;
		$sort = I("sort", 0, "intval");
		$id = I("id", 0, "intval");
		
		$d = D($varModel);
		if ($d->where("id={$id}")->setField($varStatus, $sort)) {
			$this->ajaxSuccess();
		} else {
			$this->ajaxError($d->getError());
		}
	}
	/**
	 * 显示分页
	 *
	 * @param integer $totalRows
	 * @param integer $listRows
	 * @param array $parameter
	 * @param string $varPage
	 * @return \Utuo\BackgroundController
	 */
	protected function showPage($totalRows, $listRows, $parameter = null, $varPage = 'pagination') {
		$page = new Page($totalRows, $listRows, $parameter);
		$pagination = $page->show();
		$this->assign($varPage, $pagination);
		return $this;
	}
	
	/**
	 * 获取指定ID的一条数据
	 *
	 * @param string $model
	 * @param integer $id
	 * @return array
	 */
	protected function getOneById($model, $id = null) {
		is_null($id) && $id = I('id');
		$id = intval($id);
		return M($model)->find("$id");
	}
	
	/**
	 * 设置模块标题
	 *
	 * @param string $title
	 * @return \Utuo\BackgroundController
	 */
	protected function setModuleTitle($title) {
		$this->moduleTitle = $title;
		return $this;
	}
	
	/**
	 * 获取模块标题
	 *
	 * @return string
	 */
	protected function getModuleTitle() {
		return isset($this->moduleTitle) ? $this->moduleTitle : MODULE_NAME;
	}
	
	/**
	 * 设置控制器标题
	 *
	 * @param string $title
	 * @return \Utuo\BackgroundController
	 */
	protected function setControllerTitle($title) {
		$this->controllerTitle = $title;
		return $this;
	}
	
	/**
	 * 获取控制器标题
	 *
	 * @return string
	 */
	protected function getControllerTitle() {
		return isset($this->controllerTitle) ? $this->controllerTitle : CONTROLLER_NAME;
	}
	
	/**
	 * 设置动作标题
	 *
	 * @param string|array $action
	 * @param string $title
	 * @return \Utuo\BackgroundController
	 */
	protected function setActionTitle($action, $title = null, $params = null) {
		if (is_array($action)) {
			$this->actionTitles = array_merge($this->actionTitles, $action);
			foreach ($action as $k => $v) {
				$this->actionTitles[$k] = $v;
				$this->actionNavParams[$k] = $params;
			}
		} else {
			$this->actionTitles[$action] = $title;
			$this->actionNavParams[$action] = $params;
		}
		return $this;
	}
	
	/**
	 * 获取动作标题
	 *
	 * @param string $action
	 * @return string
	 */
	protected function getActionTitle($action = null) {
		is_null($action) && $action = ACTION_NAME;
		return isset($this->actionTitles[$action]) ? $this->actionTitles[$action] : $action;
	}
	
	/**
	 * 获取当前位置路径
	 *
	 * @return array
	 */
	protected function getPositionPath() {
		$path = array ();
// 		$path[] = array (
// 				'name' => $this->getModuleTitle(),
// 				'url' => __MODULE__ 
// 		);
		$path[] = array (
				'name' => $this->getControllerTitle(),
				'url' => __CONTROLLER__ 
		);
		$path[] = array (
				'name' => $this->getActionTitle(),
				'url' => __ACTION__ 
		);
		return $path;
	}
	
	/**
	 * 设置动作导航
	 *
	 * @param string|array $action
	 * @return \Utuo\BackgroundController
	 */
	protected function setActionNav($action) {
		if ($action === false) {
			$this->actionNavs = array ();
		} else {
			is_string($action) && $action = explode(',', $action);
			$this->actionNavs = array_merge($this->actionNavs, $action);
		}
		return $this;
	}
	
	/**
	 * 移除动作导航
	 *
	 * @param string|array $action
	 */
	protected function removeActionNav($action) {
		$action = (array) $action;
		foreach ($this->actionNavs as $k => $v) {
			if (in_array($v, $action)) {
				unset($this->actionNavs[$k]);
			}
		}
		return $this;
	}
	
	/**
	 * 回收站
	 */
	public function recycleAction() {
		$this->getLists(1);
	}
	
	/**
	 * 列表
	 */
	public function indexAction() {
		$this->getLists(0);
	}
	/**
	 * 恢复数据（从回收站里恢复）
	 *
	 * @param string $varModel
	 * @param string $msgError
	 * @param string $msgSucc
	 * @param string $varPK
	 * @param string $varField
	 */
	
	/**
	 * 获取动作导航数组
	 *
	 * @return array
	 */
	protected function getActionNavs() {
		$lists = array ();
		foreach ($this->actionNavs as $action) {
			$param = isset($this->actionNavParams[$action]) ? $this->actionNavParams[$action] : '';
			$lists[] = array (
					'name' => $this->getActionTitle($action),
					'url' => U(CONTROLLER_NAME . '/' . $action, $param),
					'active' => $action == ACTION_NAME 
			);
		}
		return $lists;
	}
	
	/**
	 * 设置链接导航标题
	 *
	 * @param string $title
	 * @return \Utuo\BackgroundController
	 */
	protected function setLinkNavTitle($title) {
		$this->linkNavTitle = $title;
		return $this;
	}
	
	/**
	 * 获取链接导航标题
	 *
	 * @return string
	 */
	protected function getLinkNavTitle() {
		return $this->linkNavTitle;
	}
	
	/**
	 * 设置链接导航
	 *
	 * @param array|string $name
	 * @param string $url
	 * @return \Utuo\BackgroundController
	 */
	protected function setLinkNav($name, $url = null) {
		if ($name === false) {
			$this->linkNavs = array ();
		} elseif (is_array($name)) {
			$this->linkNavs = array_merge($this->linkNavs, $name);
		} else {
			$this->linkNavs[] = array (
					'name' => $name,
					'url' => $url 
			);
		}
		return $this;
	}
	
	/**
	 * 获取链接导航数组
	 *
	 * @return array
	 */
	protected function getLinkNavs() {
		return $this->linkNavs;
	}
	
	/**
	 * 是否有管理权限
	 *
	 * @param integer $id 当前操作记录的所属ID
	 * @param integer $adminId 具有管理权限的ID，默认为当前登录管理员
	 * @param string $errMsg 错误提示信息
	 * @return boolean
	 */
	protected function checkAdmin($id, $model = null, $field = null) {
		if (is_null($id)) {
			$id = $model->where("id=%d", I("id", 0, "intval"))->getField($field);
		}
		$errMsg = "没有管理权限";
		if (intval($id) != $this->aid) {
			if (IS_AJAX) {
				$this->ajaxError($errMsg);
			} else {
				$this->error($errMsg);
			}
			return false;
		}
		return true;
	}
	
	/**
	 * 检测登录状态，未登录则跳转
	 *
	 * @return boolean
	 */
	private function checkLogin() {
		if ($this->isLogined()) {
			if (strtolower(CONTROLLER_NAME) == C('LOGIN_CONTROLLER') and strtolower(ACTION_NAME) == C('LOGIN_ACTION')) { // 登录页刷新
				redirect(U("Index/index"));
			}
			return true;
		} else {
			$this->loginLog and $this->loginLog->out(array (
					'admin_id' => session(C("USER_AUTH_KEY")),
					'session_id' => session_id() 
			));
		}
		if (strtolower(CONTROLLER_NAME) == C('LOGIN_CONTROLLER')) {
			return true;
		}
		redirect(U(sprintf('%s/%s/%s', MODULE_NAME, C('LOGIN_CONTROLLER'), C('LOGIN_ACTION'))), self::$redirectTime, self::$redirectMessage);
	}
	
	/**
	 * 设置消息
	 *
	 * @param string $message
	 */
	private static function setMessage($message, $time = 0) {
		self::$redirectMessage = $message;
		self::$redirectTime = $time;
	}
	
	/**
	 * 检测是否登录
	 *
	 * @return boolean
	 */
	private function isLogined() {
		$now = time();
		if (session(self::IS_LOGINED)) {
			if (time() - session(self::LAST_ACTIVE) > C('LOGIN_AGE')) {
				return false;
			}
			
			// 检测是否重复登录
			$adminId = $this->getAdminId();
			if (!C('LOGIN_REPEATABLE') and session(self::LOGIN_LABEL) and $adminId) {
				if (session(self::LOGIN_TIME) != F(session(self::LOGIN_LABEL))) {
					self::setMessage("重复登录，您被迫下线，请重新登录！", 3);
					session(null);
					return false;
				}
			}
			
			// 记录最后登录时间
			$preLastTime = session(self::LAST_ACTIVE);
			$this->aid = session('id');
			$this->aname = session('name');
			$this->adminId = $adminId;
			if (($now - $preLastTime) > 10) { // 10秒记录一次
				session(self::LAST_ACTIVE, time());
				$this->loginLog and $this->loginLog->active(array (
						'admin_id' => $this->adminId,
						'session_id' => session_id() 
				));
			}
			return true;
		}
		return false;
	}
	
	/**
	 * 获得管理员id
	 */
	private function getAdminId() {
		$this->adminId = C('USER_AUTH_KEY') ? (session(C('USER_AUTH_KEY')) ? session(C('USER_AUTH_KEY')) : 0) : 0;
		return $this->adminId * 1;
	}
	
	/**
	 * 设置登录SESSION信息
	 *
	 * @param string $id
	 * @param string $name
	 * @param string $value
	 * @return \Utuo\BackgroundController
	 */
	protected function setLogin($uid, $name, $data = null) {
		$time = time();
		$adminId = C('USER_AUTH_KEY') ? ($data[C('USER_AUTH_KEY')] ? $data[C('USER_AUTH_KEY')] : 0) : 0;
		session(self::IS_LOGINED, true);
		session(self::LAST_ACTIVE, time());
		$this->sessionKeys = array (
				self::IS_LOGINED,
				self::LAST_ACTIVE,
				'id',
				'name',
				'customerManagerConfig' 
		);
		session('id', $uid);
		session('name', $name);
		session(self::LOGIN_TIME, $time);
		session(self::LOGIN_LABEL, sprintf('__login__%s__%s', C('SESSION_PREFIX'), $adminId));
		F(session(self::LOGIN_LABEL), $time);
		if (isset($data) && is_array($data)) {
			foreach ($data as $k => $v) {
				session($k, $v);
				$this->sessionKeys[] = $k;
			}
		}
		session("sessionKeys", serialize($this->sessionKeys));
		$this->loginLog and $this->loginLog->log(array (
				'id' => $uid,
				'admin_id' => $adminId,
				'session_id' => session_id() 
		));
		return $this;
	}
	
	/**
	 * 退出登录，删除登录SESSION信息
	 *
	 * @return \Utuo\BackgroundController
	 */
	protected function setLogout() {
		if (session("sessionKeys"))
			$this->sessionKeys = unserialize(session("sessionKeys"));
		else
			$this->sessionKeys = array ();
		$this->loginLog and $this->loginLog->out(array (
				'admin_id' => session(C("USER_AUTH_KEY")),
				'session_id' => session_id() 
		));
		foreach ($this->sessionKeys as $name) {
			session($name, null);
		}
		return $this;
	}
	
	/**
	 * 获取表单选择列表
	 *
	 * @param array $options
	 * @param string $default
	 * @param string $firstOption
	 * @return string
	 */
	protected function getOption($options, $default = null, $firstOption = null) {
		empty($options) && $options = array ();
		$ret = array ();
		empty($firstOption) or $ret[] = "<option value=''>$firstOption</option>";
		foreach ($options as $k => $v) {
			$selected = !is_null($default) && $default == $k ? " selected='selected'" : '';
			$ret[] = "<option value='$k' $selected>$v</option>";
		}
		return implode("\n", $ret);
	}
	
	/**
	 * 获取单选表单
	 *
	 * @param string $name
	 * @param array $options
	 * @param string $default
	 * @return string
	 */
	protected function getRadio($name, $options, $default = null) {
		$ret = array ();
		foreach ($options as $k => $v) {
			$checked = !is_null($default) && $default == $k ? " checked='checked'" : '';
			$ret[] = "<label title='$v'><input type='radio' name='$name' id='{$name}_$k' value='$k' $checked datatype='*'> $v</label>";
		}
		return implode("\n", $ret);
	}
	
	/**
	 * 获取多选表单
	 *
	 * @param string $name
	 * @param array $options
	 * @param string $default
	 * @return string
	 */
	protected function getCheckBox($name, $options, $default = array()) {
		$default == null and $default = array ();
		!is_array($default) and $default = array (
				$default 
		);
		$ret = array ();
		foreach ($options as $k => $v) {
			$checked = !is_null($default) && in_array($k, $default) == $k ? " checked='checked'" : '';
			$ret[] = "<label><input type='checkbox' name='$name' id='{$name}_$k' value='$k'$checked> $v</label>";
		}
		return implode("\n", $ret);
	}
	
	/**
	 * 获得当前页码
	 *
	 * @return int
	 */
	protected function getPage() {
		return I('p', 1, 'intval');
	}
	
	/**
	 * 获取分页大小
	 *
	 * @return number
	 */
	protected function getPageSize() {
		return I('pagesize', $this->pageSize, 'intval');
	}
	
	/**
	 * 获取id
	 *
	 * @param string $varId
	 * @param number $default
	 * @return integer
	 */
	protected function getId($varId = 'id', $default = 0) {
		return I($varId, $default, 'intval');
	}
	
	/**
	 * 创建验证码
	 *
	 * @param unknown $id
	 */
	protected function createVerify($id) {
		$Verify = new \Think\Verify();
		$Verify->fontttf = '5.ttf';
		$Verify->fontSize = 15;
		$Verify->length = 4;
		$Verify->imageW = 120;
		$Verify->imageH = 34;
		$Verify->useNoise = false;
		$Verify->entry($id);
	}
	// 检查用户权限控制
	public function checkAuth() {
		$tableNames = \Utuo\Rbac::getAuthModelNames();
		$userid = $this->adminId;
		$data = M($tableNames['admin'][1])->where("is_role=1")->getField('id', true);
		if (in_array($userid, $data)) {
			$notAuth = in_array(CONTROLLER_NAME, explode(",", C('NOT_AUTH_MODULE'))) || in_array(ACTION_NAME, explode(",", C('NOT_AUTH_ACTION')));
			if (C('ADMIN_AUTH_KEY')) {
				$isSuperAdmin = session(C('ADMIN_AUTH_KEY')) == C('RBAC_SUPERADMIN') ? true : false;
			}
			
			if (C('USER_AUTH_ON') and !$notAuth) {
				$fun = IS_AJAX ? 'ajaxError' : 'error';
				\Utuo\Rbac::AccessDecision(MODULE_NAME) || $this->$fun('没有权限');
			}
		}
	}
	/**
	 * 显示信息
	 *
	 * @param unknown $msg
	 */
	protected function showMessage($msg) {
		if (!headers_sent()) {
			header("Content-Type:text/html;charset=utf-8");
		}
		exit($msg);
	}
	
	/**
	 * 获得简单JSON数组
	 * 
	 * @param unknown $cid
	 */
	function getSimpleJSON($data, $field = array("id", "pid", "name")) {
		$json = "[";
		for($i = 0; $i < count($data); $i++) {
			$result = array ();
			foreach ($field as $v) {
				$result[$v] = $data[$i][$v];
			}
			$json .= json_encode($result);
			if ($i < count($data) - 1) {
				$json .= ",";
			}
		}
		$json .= "]";
		return $json;
	}
	
	// 提交修改菜单
	public function submitPost($model) {
		$model = is_object($model) ? $model : D($model);
		if ($model->isCreated or $model->create()) {
			if (empty($_REQUEST['id'])) {
				unset($model->id);
				// $authField = C("AUTH_FIELD") and $model->$authField = $this->aid;
				if ($model->add()) {
					$this->ajaxSuccess("添加成功！");
				} else {
					$this->ajaxError("添加失败！" . $model->getError() . $model->getLastSql());
				}
			} else {
				if (false !== $model->save()) {
					$this->ajaxSuccess("修改成功！");
				} else {
					$this->ajaxError("修改失败！");
				}
			}
		} else {
			$this->ajaxError($model->getError());
		}
	}
	
	/**
	 * 获得管理界面配置
	 * 
	 * @return Ambigous <multitype:string , mixed, NULL>
	 */
	protected function getManagerConfig() {
		$id = $this->aid or $id = I("id", 0, 'intval');
		$customerManagerConfig = array ();
		if (session("customerManagerConfig")) {
			$customerManagerConfig = session("customerManagerConfig");
		} else {
			$id and $customerManagerConfig = M("CustomerManagerConfig")->find($id) and $saveSession = true;
			$imgstr = trim($customerManagerConfig['backgroundimgs'], " ,");
			$customerManagerConfig['backgroundimgs'] = json_encode(empty($imgstr) ? array () : explode('\r\n', $imgstr));
			if ($saveSession)
				session("customerManagerConfig", $customerManagerConfig);
		}
		$this->assign("customerManagerConfig", $customerManagerConfig);
		return $customerManagerConfig;
	}
}
class Event {
	public $eventName = "";
	public $data = null;
	public function __construct($eventName, $data) {
		$this->eventName = $eventName;
		$this->data = $data;
	}
}